<template>
  <div class="modal-backdrop" v-if="visible" @click.self="handleClose">
    <div class="modal-container" :class="{ 'modal-container--visible': visible }">
      <!-- 标题栏 -->
      <div class="modal-header">
        <div class="modal-title">
          <span class="order-number">订单 #{{ order.orderNumber }}</span>
          <span class="status-badge" :class="`status-badge--${order.status}`">
            {{ getStatusLabel(order.status) }}
          </span>
        </div>
        <button class="close-btn" @click="handleClose">
          <i class="fas fa-times"></i>
        </button>
      </div>
      
      <!-- 内容区域 -->
      <div class="modal-body" v-if="!loading">
        <!-- 基本信息区域 -->
        <div class="section">
          <h3 class="section-title">
            <i class="fas fa-info-circle"></i> 基本信息
          </h3>
          <div class="info-grid">
            <div class="info-item">
              <div class="info-label">创建时间</div>
              <div class="info-value">{{ formatDate(order.createdAt) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">支付时间</div>
              <div class="info-value">
                {{ order.paymentInfo.paymentTime ? formatDate(new Date(order.paymentInfo.paymentTime)) : '未支付' }}
              </div>
            </div>
            <div class="info-item">
              <div class="info-label">餐厅</div>
              <div class="info-value restaurant">
                <img :src="order.restaurant.image" alt="餐厅图片" class="restaurant-image">
                <span>{{ order.restaurant.name }}</span>
              </div>
            </div>
            <div class="info-item">
              <div class="info-label">顾客</div>
              <div class="info-value">{{ order.customer.name }}</div>
            </div>
          </div>
        </div>
        
        <!-- 商品信息区域 -->
        <div class="section">
          <h3 class="section-title">
            <i class="fas fa-shopping-cart"></i> 商品信息
          </h3>
          <div class="products-list">
            <div class="product-item" v-for="(item, index) in order.items" :key="index">
              <div class="product-image">
                <img :src="item.image" :alt="item.name">
              </div>
              <div class="product-details">
                <div class="product-name">{{ item.name }}</div>
                <div class="product-price">
                  <span class="discount-price">¥{{ formatNumber(item.discountPrice) }}</span>
                  <span class="original-price">¥{{ formatNumber(item.price) }}</span>
                </div>
              </div>
              <div class="product-quantity">
                x{{ item.quantity }}
              </div>
              <div class="product-total">
                ¥{{ formatNumber(item.discountPrice * item.quantity) }}
              </div>
            </div>
            
            <div class="order-total">
              <div class="total-row">
                <span>商品总价</span>
                <span>¥{{ formatNumber(order.commissionCalculation.originalTotal) }}</span>
              </div>
              <div class="total-row">
                <span>折扣金额</span>
                <span class="discount-amount">-¥{{ formatNumber(order.commissionCalculation.discountAmount) }}</span>
              </div>
              <div class="total-row final-total">
                <span>实付金额</span>
                <span>¥{{ formatNumber(order.totalAmount) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 佣金计算区域 -->
        <div class="section">
          <h3 class="section-title">
            <i class="fas fa-calculator"></i> 佣金信息
          </h3>
          <div class="commission-card">
            <div class="commission-calculation">
              <div class="calculation-row">
                <div class="calculation-label">原价总额</div>
                <div class="calculation-value">¥{{ formatNumber(order.commissionCalculation.originalTotal) }}</div>
              </div>
              <div class="calculation-row">
                <div class="calculation-label">折扣总额</div>
                <div class="calculation-value">¥{{ formatNumber(order.commissionCalculation.discountTotal) }}</div>
              </div>
              <div class="calculation-row">
                <div class="calculation-label">折扣金额</div>
                <div class="calculation-value discount-amount">¥{{ formatNumber(order.commissionCalculation.discountAmount) }}</div>
              </div>
              <div class="calculation-row">
                <div class="calculation-label">佣金比例</div>
                <div class="calculation-value commission-rate">{{ order.commissionCalculation.commissionRate }}</div>
              </div>
              <div class="calculation-row final-commission">
                <div class="calculation-label">佣金金额</div>
                <div class="calculation-value commission-amount">¥{{ formatNumber(order.commissionCalculation.commissionAmount) }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 支付信息区域 -->
        <div class="section">
          <h3 class="section-title">
            <i class="fas fa-credit-card"></i> 支付信息
          </h3>
          <div class="payment-info">
            <div class="payment-row">
              <div class="payment-label">支付方式</div>
              <div class="payment-value">{{ getPaymentMethod(order.paymentInfo.method) }}</div>
            </div>
            <div class="payment-row">
              <div class="payment-label">交易ID</div>
              <div class="payment-value transaction-id">{{ order.paymentInfo.transactionId || '暂无' }}</div>
            </div>
            <div class="payment-row">
              <div class="payment-label">支付状态</div>
              <div class="payment-value" :class="`payment-status--${order.paymentInfo.status === '已支付' ? 'paid' : 'pending'}`">
                {{ order.paymentInfo.status }}
              </div>
            </div>
            <div class="payment-row" v-if="order.paymentLink">
              <div class="payment-label">支付链接</div>
              <div class="payment-value payment-link">
                <span class="link-text">{{ order.paymentLink.name }}</span>
                <button class="copy-link-btn" @click="copyLink(order.paymentLink.url)">
                  <i class="fas fa-copy"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 订单状态历史区域 -->
        <div class="section">
          <h3 class="section-title">
            <i class="fas fa-history"></i> 订单状态历史
          </h3>
          <div class="status-timeline">
            <div class="timeline-item" v-for="(item, index) in order.statusHistory" :key="index" :class="`timeline-item--${item.status}`">
              <div class="timeline-icon">
                <i class="fas" :class="getStatusIcon(item.status)"></i>
              </div>
              <div class="timeline-content">
                <div class="timeline-header">
                  <span class="timeline-title">{{ item.label }}</span>
                  <span class="timeline-time">{{ formatDate(new Date(item.time)) }}</span>
                </div>
                <div class="timeline-description">{{ item.description }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div class="modal-body loading-state" v-else>
        <div class="loading-spinner">
          <i class="fas fa-spinner fa-spin"></i>
          <span>加载订单详情...</span>
        </div>
      </div>
      
      <!-- 底部按钮 -->
      <div class="modal-footer">
        <button class="export-btn" @click="handleExport">
          <i class="fas fa-file-export"></i> 导出订单
        </button>
        <button class="close-btn-secondary" @click="handleClose">
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from 'vue'
import { generateOrderDetailData } from '@/utils/mockData'

interface Props {
  visible: boolean
  orderId?: string
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'export', order: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  orderId: ''
})

const emit = defineEmits<Emits>()

// 内部状态
const loading = ref(true)
const order = ref<any>({
  orderNumber: '',
  status: 'pending',
  createdAt: '',
  items: [],
  totalAmount: 0,
  customer: { name: '' },
  restaurant: { name: '', image: '' },
  paymentInfo: { method: '', transactionId: '', paymentTime: null, status: '待支付' },
  commissionCalculation: { originalTotal: 0, discountTotal: 0, discountAmount: 0, commissionRate: '0%', commissionAmount: 0 },
  statusHistory: []
})

// 加载订单详情
const loadOrderDetail = async () => {
  if (!props.orderId) return
  
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    const data = generateOrderDetailData(props.orderId)
    order.value = data
  } catch (error) {
    console.error('获取订单详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听订单ID变化
watch(() => props.orderId, () => {
  if (props.visible && props.orderId) {
    loadOrderDetail()
  }
})

// 监听可见性变化
watch(() => props.visible, (newValue) => {
  if (newValue && props.orderId) {
    loadOrderDetail()
  }
})

// 格式化数字
const formatNumber = (num: number) => {
  return num.toFixed(2)
}

// 格式化日期
const formatDate = (date: string | Date) => {
  const d = new Date(date)
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  switch (status) {
    case 'completed': return '已完成'
    case 'processing': return '处理中'
    case 'pending': return '待处理'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 获取支付方式
const getPaymentMethod = (method: string) => {
  switch (method) {
    case 'paypal': return 'PayPal'
    case 'credit_card': return '信用卡'
    case 'alipay': return '支付宝'
    case 'wechat': return '微信支付'
    default: return method
  }
}

// 获取状态图标
const getStatusIcon = (status: string) => {
  switch (status) {
    case 'created': return 'fa-file'
    case 'paid': return 'fa-money-bill'
    case 'processing': return 'fa-hourglass-half'
    case 'completed': return 'fa-check-circle'
    case 'cancelled': return 'fa-times-circle'
    default: return 'fa-circle'
  }
}

// 复制链接
const copyLink = (link: string) => {
  navigator.clipboard.writeText(link).then(() => {
    alert('链接已复制到剪贴板')
  }).catch(() => {
    alert('复制失败，请手动复制')
  })
}

// 关闭模态框
const handleClose = () => {
  emit('update:visible', false)
}

// 导出订单
const handleExport = () => {
  emit('export', order.value)
  alert('订单导出功能开发中')
}
</script>

<style scoped lang="scss">
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  overflow-y: auto;
}

.modal-container {
  background-color: #fff;
  border-radius: 12px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.3s;
  overflow: hidden;
  
  &--visible {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .modal-title {
    display: flex;
    align-items: center;
    
    .order-number {
      font-size: 18px;
      font-weight: 700;
      color: #2F3542;
      margin-right: 12px;
    }
    
    .status-badge {
      display: inline-block;
      padding: 4px 10px;
      border-radius: 15px;
      font-size: 13px;
      font-weight: 500;
      
      &--completed {
        background-color: #e8f7ef;
        color: #28A745;
      }
      
      &--processing {
        background-color: #e8f2ff;
        color: #007BFF;
      }
      
      &--pending {
        background-color: #fff8e6;
        color: #FFC107;
      }
      
      &--cancelled {
        background-color: #ffe8e8;
        color: #DC3545;
      }
    }
  }
  
  .close-btn {
    background: none;
    border: none;
    color: #6C757D;
    font-size: 18px;
    cursor: pointer;
    transition: color 0.2s;
    
    &:hover {
      color: #212529;
    }
  }
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
  
  &.loading-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
    
    .loading-spinner {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #6C757D;
      
      i {
        font-size: 32px;
        margin-bottom: 16px;
        color: #FF4757;
      }
    }
  }
}

.section {
  margin-bottom: 24px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #2F3542;
    margin: 0 0 16px 0;
    display: flex;
    align-items: center;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
    
    i {
      margin-right: 8px;
      color: #FF4757;
    }
  }
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
  
  .info-item {
    .info-label {
      font-size: 13px;
      color: #6C757D;
      margin-bottom: 4px;
    }
    
    .info-value {
      font-size: 15px;
      color: #2F3542;
      
      &.restaurant {
        display: flex;
        align-items: center;
        
        .restaurant-image {
          width: 24px;
          height: 24px;
          border-radius: 4px;
          margin-right: 8px;
          object-fit: cover;
        }
      }
    }
  }
}

.products-list {
  .product-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .product-image {
      width: 48px;
      height: 48px;
      border-radius: 6px;
      overflow: hidden;
      margin-right: 12px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .product-details {
      flex: 1;
      
      .product-name {
        font-size: 14px;
        color: #2F3542;
        margin-bottom: 4px;
      }
      
      .product-price {
        display: flex;
        align-items: center;
        
        .discount-price {
          font-size: 14px;
          color: #FF4757;
          font-weight: 500;
          margin-right: 8px;
        }
        
        .original-price {
          font-size: 13px;
          color: #ADB5BD;
          text-decoration: line-through;
        }
      }
    }
    
    .product-quantity {
      font-size: 14px;
      color: #6C757D;
      margin: 0 16px;
    }
    
    .product-total {
      font-size: 15px;
      font-weight: 600;
      color: #2F3542;
      min-width: 70px;
      text-align: right;
    }
  }
  
  .order-total {
    border-top: 1px solid #eee;
    padding-top: 16px;
    margin-top: 16px;
    
    .total-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      font-size: 14px;
      color: #6C757D;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .discount-amount {
        color: #FF4757;
      }
      
      &.final-total {
        font-size: 16px;
        font-weight: 600;
        color: #2F3542;
        padding-top: 8px;
        border-top: 1px dashed #eee;
      }
    }
  }
}

.commission-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
  
  .commission-calculation {
    .calculation-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      font-size: 14px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .calculation-label {
        color: #6C757D;
      }
      
      .calculation-value {
        font-weight: 500;
        color: #2F3542;
        
        &.discount-amount {
          color: #FF4757;
        }
        
        &.commission-rate {
          color: #007BFF;
        }
        
        &.commission-amount {
          color: #28A745;
        }
      }
      
      &.final-commission {
        font-size: 16px;
        font-weight: 600;
        padding-top: 12px;
        border-top: 1px dashed #ddd;
        
        .calculation-label {
          color: #212529;
        }
      }
    }
  }
}

.payment-info {
  .payment-row {
    display: flex;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .payment-label {
      width: 100px;
      font-size: 14px;
      color: #6C757D;
    }
    
    .payment-value {
      flex: 1;
      font-size: 14px;
      color: #2F3542;
      
      &.transaction-id {
        font-family: monospace;
      }
      
      &.payment-status--paid {
        color: #28A745;
        font-weight: 500;
      }
      
      &.payment-status--pending {
        color: #FFC107;
        font-weight: 500;
      }
      
      &.payment-link {
        display: flex;
        align-items: center;
        
        .link-text {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .copy-link-btn {
          background: none;
          border: none;
          color: #007BFF;
          cursor: pointer;
          margin-left: 8px;
          
          &:hover {
            color: #0056b3;
          }
        }
      }
    }
  }
}

.status-timeline {
  position: relative;
  padding-left: 30px;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    left: 11px;
    width: 2px;
    background-color: #ddd;
  }
  
  .timeline-item {
    position: relative;
    padding-bottom: 24px;
    
    &:last-child {
      padding-bottom: 0;
    }
    
    &:last-child::after {
      display: none;
    }
    
    .timeline-icon {
      position: absolute;
      top: 0;
      left: -30px;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 2;
      
      i {
        font-size: 12px;
      }
    }
    
    &--created .timeline-icon {
      background-color: #17A2B8;
      color: #fff;
    }
    
    &--paid .timeline-icon {
      background-color: #007BFF;
      color: #fff;
    }
    
    &--processing .timeline-icon {
      background-color: #FFC107;
      color: #212529;
    }
    
    &--completed .timeline-icon {
      background-color: #28A745;
      color: #fff;
    }
    
    &--cancelled .timeline-icon {
      background-color: #DC3545;
      color: #fff;
    }
    
    .timeline-content {
      padding-bottom: 8px;
      
      .timeline-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 4px;
        
        @media (max-width: 576px) {
          flex-direction: column;
          align-items: flex-start;
        }
        
        .timeline-title {
          font-size: 15px;
          font-weight: 600;
          color: #2F3542;
        }
        
        .timeline-time {
          font-size: 13px;
          color: #6C757D;
        }
      }
      
      .timeline-description {
        font-size: 14px;
        color: #6C757D;
      }
    }
  }
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  .export-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 8px 16px;
    background-color: #FF4757;
    color: #fff;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    
    i {
      margin-right: 6px;
    }
    
    &:hover {
      background-color: darken(#FF4757, 10%);
    }
  }
  
  .close-btn-secondary {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 8px 20px;
    background-color: #F8F9FA;
    color: #2F3542;
    border: 1px solid #DFE3E8;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    
    &:hover {
      background-color: #E9ECEF;
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .modal-container {
    width: 95%;
    max-height: 95vh;
  }
  
  .modal-header {
    padding: 12px 16px;
    
    .modal-title {
      .order-number {
        font-size: 16px;
      }
    }
  }
  
  .modal-body {
    padding: 16px;
  }
  
  .product-item {
    flex-wrap: wrap;
    
    .product-details {
      width: calc(100% - 60px);
    }
    
    .product-quantity,
    .product-total {
      margin-top: 8px;
      margin-left: 60px;
    }
    
    .product-quantity {
      flex: 1;
    }
  }
  
  .payment-info {
    .payment-row {
      flex-direction: column;
      
      .payment-label {
        width: 100%;
        margin-bottom: 4px;
      }
    }
  }
  
  .modal-footer {
    padding: 12px 16px;
    flex-direction: column;
    
    .export-btn,
    .close-btn-secondary {
      width: 100%;
    }
  }
}
</style> 